import { createApp, type Component, type App } from 'vue';

interface ComponentContainer {
  container: HTMLElement | null;
  component: Component | null;
}

interface ComponentManager {
  create(component: Component, container: HTMLElement): void;
  remove(container: HTMLElement): void;
}

const manager: ComponentManager = {
  create(component: Component, container: HTMLElement) {
    let item = componentContainers.find(item => item.container === container);
    if (!item) {
      item = { container, component };
      componentContainers.push(item);
    } else {
      item.component = component;
    }

    const app = createApp(component);
    app.mount(container);
  },

  remove(container: HTMLElement) {
    const index = componentContainers.findIndex(item => item.container === container);
    if (index === -1) {
      return;
    }

    // 销毁根组件
    const root = componentContainers[index];
    const app = root.component ? root.component.appContext.app : null;
    app && app.unmount();
    componentContainers.splice(index, 1);
  }
};

let componentContainers: ComponentContainer[] = [];

// 在main.js中使用 plugin 安装全局方法
function install(app: App) {
  app.config.globalProperties.$window = manager;
  // app.config.globalProperties.$remove = manager.remove;
}

export default install;